import otherHelpers from "./others";
import autoDisposeWhenUnload from "./autoDisposeWhenUnload";

const waitList = [];
const dataList = [];

autoDisposeWhenUnload(function () {
    waitList.forEach(w => w?.destroy());
    waitList.splice(0, waitList.length);
    dataList.splice(0, dataList.length);
});

export default class WaitMinTime {
    constructor() {
        waitList.push(this);
        dataList.push(1600);
    }

    set endTime(t) {
        dataList[waitList.indexOf(this)] = t;
    }

    get endTime() {
        return dataList[waitList.indexOf(this)];
    }

    start(minWaitMs = 1600) {
        this.endTime = minWaitMs + Date.now();
    }

    async end() {
        const diff = Date.now() - this.endTime;
        if (0 < diff) {
            await new Promise(r => otherHelpers.globalThis.setTimeout(r, diff));
        }
    }

    destroy() {
        const index = waitList.indexOf(this);
        waitList[index] = null;
        dataList[index] = null;
    }
}
